var cluster = require('cluster');
var os = require('os');
//获取cpu的数量
var numCPUs = os.cpus().length;
//工作进程对象
var workers = {};
if (cluster.isMaster) {
    //主进程分支
    cluster.on('death', function (worker) {
        //当一个工作进程结束时,重启工作进程
        delete workers[worker.pid];
        worker = cluster.fork();
        workers[worker.pid] = worker;
    });
    //启动与cpu数量相同的工作进程
    for (var i = 0; i < numCPUs; i++) {
        var worker = cluster.fork();
        workers[worker.pid] = worker;
        console.log("开启第"+ i +"个进程成功,进程pid为"+ worker.pid);
    }
}else{
    //工作进程分支,启动服务
    var app = require('./index');
    app.listen(process.env.PORT || 1337);
}

//当主进程被终止时,关闭所有工作进程
process.on('SIGTERM', function () {
    for (var pid in workers) {
        process.kill(pid);
}

process.exit(0);
});